home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17098 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.6 KB  |  68 lines

  1. Newsgroups: comp.lang.c++
  2. Path: newsfeed.internetmci.com!miwok!linex1!news
  3. From: mfried@linex.com (Marty Fried)
  4. Subject: Re: HELP: A basic question
  5. X-Nntp-Posting-Host: sp106.linex.com
  6. Message-ID: <316ff292.4129426@news.linex.com>
  7. Sender: news@linex1.linex.com
  8. Organization: Cirrius Cybernetics Corp
  9. X-Newsreader: Forte Agent .99e/32.209
  10. References: <4kfl8c$nju@falcon.ccs.uwo.ca>
  11. Date: Sat, 13 Apr 1996 18:38:49 GMT
  12.  
  13. Once upon a time (OK, it was 10 Apr 1996 06:42:20 GMT), Sharon Wang
  14. <swang1@julian.uwo.ca> wrote:
  15.  
  16. >hello worlf, i have the following code which compiles ok but causes
  17. >segmentation fault:
  18. >
  19. >class T{
  20. >    ...
  21. >public:
  22. >    ...
  23. >    T deform();
  24. >};
  25. >
  26. >T T::deform(void)
  27. >{
  28. >    T c;
  29. >    ...
  30. >    return c;  // guess something wrong here
  31. >}
  32. >
  33. >int main(void)
  34. >{
  35. >    T a, b;
  36. >    ...
  37. >    b = a.deform();  // ERROR: segmentation fault! ('=' overloaded ok)
  38. >}
  39. >
  40. >can anyone tell me what's wrong with the code, or please tell me
  41. >if this is not the right place to post.
  42.  
  43. One problem I see is the body of deform - you are declaring a c as a
  44. stack variable of type T, meaning it is destroyed at the end of the
  45. function, yet you are returning it after it is destroyed.  You could
  46. use new, and return a pointer.
  47. ie
  48. T *T::deform()
  49. {
  50.    T *c = new T;
  51.    return c;
  52. }
  53.  
  54. int main()
  55. {
  56.     T a, *b;
  57.     b = a.deform();
  58. }
  59. Be sure to delete b when done.
  60.  
  61. There may be another way, but this was the simplest I thought of right
  62. off the bat.
  63.  
  64. _______________________________________________________
  65. Marty Fried - mfried@linex.com     Press Enter to Exit
  66. San Anselmo, CA                           -NT message
  67. (MSVC4 + MFC) && (Win95 || NT);             
  68.